"""
收藏相关API路由
"""
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import List
from app.database import get_db
from app import models, schemas

router = APIRouter()


@router.post("/favorites", response_model=schemas.FavoriteResponse)
async def create_favorite(
    favorite: schemas.FavoriteCreate,
    db: Session = Depends(get_db)
):
    """
    添加收藏
    
    - **user_id**: 用户ID
    - **work_id**: 作品ID
    """
    # 检查作品是否存在
    work = db.query(models.Work).filter(models.Work.id == favorite.work_id).first()
    if not work:
        raise HTTPException(status_code=404, detail="作品不存在")
    
    # 检查用户是否存在
    user = db.query(models.User).filter(models.User.id == favorite.user_id).first()
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    # 检查是否已收藏
    existing = db.query(models.Favorite).filter(
        models.Favorite.user_id == favorite.user_id,
        models.Favorite.work_id == favorite.work_id
    ).first()
    
    if existing:
        raise HTTPException(status_code=400, detail="已经收藏过该作品")
    
    # 创建收藏
    db_favorite = models.Favorite(
        user_id=favorite.user_id,
        work_id=favorite.work_id
    )
    db.add(db_favorite)
    db.commit()
    db.refresh(db_favorite)
    
    # 返回包含作品信息的收藏
    db.refresh(db_favorite)
    return db_favorite


@router.get("/favorites", response_model=List[schemas.FavoriteResponse])
async def get_favorites(
    user_id: int = Query(..., description="用户ID"),
    skip: int = Query(0, ge=0, description="跳过记录数"),
    limit: int = Query(10, ge=1, le=100, description="返回记录数"),
    db: Session = Depends(get_db)
):
    """
    获取用户的收藏列表
    
    - **user_id**: 用户ID
    - **skip**: 分页偏移量
    - **limit**: 每页数量
    """
    favorites = db.query(models.Favorite).filter(
        models.Favorite.user_id == user_id
    ).order_by(models.Favorite.created_at.desc()).offset(skip).limit(limit).all()
    
    return favorites


@router.delete("/favorites/{favorite_id}")
async def delete_favorite(
    favorite_id: int,
    user_id: int = Query(..., description="用户ID"),
    db: Session = Depends(get_db)
):
    """
    取消收藏
    
    - **favorite_id**: 收藏ID
    - **user_id**: 用户ID（用于验证权限）
    """
    favorite = db.query(models.Favorite).filter(
        models.Favorite.id == favorite_id,
        models.Favorite.user_id == user_id
    ).first()
    
    if not favorite:
        raise HTTPException(status_code=404, detail="收藏记录不存在")
    
    db.delete(favorite)
    db.commit()
    return {"message": "已取消收藏"}


@router.get("/favorites/check")
async def check_favorite(
    user_id: int = Query(..., description="用户ID"),
    work_id: int = Query(..., description="作品ID"),
    db: Session = Depends(get_db)
):
    """
    检查用户是否已收藏某个作品
    
    - **user_id**: 用户ID
    - **work_id**: 作品ID
    """
    favorite = db.query(models.Favorite).filter(
        models.Favorite.user_id == user_id,
        models.Favorite.work_id == work_id
    ).first()
    
    return {
        "is_favorited": favorite is not None,
        "favorite_id": favorite.id if favorite else None
    }

